package com.wits.comet.chat.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.AsyncContext;

import org.springframework.stereotype.Component;

import com.wits.comet.chat.common.CometCommand;
import com.wits.comet.chat.common.CometDomain;
import com.wits.comet.chat.entity.ChatMember;
import com.wits.platform.common.utils.DateUtil;
import com.wits.platform.service.account.ShiroUser;
import com.wits.qso.entity.DiscussItems;
import com.wits.qso.service.GroupCache;

@Component
public class ChatRoomService {

	/**
	 * @param memberIdList
	 *            接受者集合
	 * @param exceptMember
	 *            排除的用户(不发送消息至该用户)
	 * @param message
	 *            广播消息
	 * @throws IOException
	 */
	public void broadcast(Collection<String> memberIdList, DiscussItems item) {
		CometContext cm = CometContext.getInstance();
		CurrentLoginUser clu=CurrentLoginUser.getInstance();
		for (String memberId : memberIdList) {
			ChatMember member = cm.getMember(memberId);
			if (member != null) {
				sendMessage(item,member);
			}else{
				//在聊天缓存成员组中找不到成员则去当前登录用户中去找，
				member=clu.getMember(memberId);
				//如果找到，就发送信息，如果没找到就继续循环，根据下一个新成员ID查找
				if(member!=null){
					sendMessage(item, member);
				}
			}
			
		}

	}

	/**
	 * 发送消息
	 * 
	 * @param item 消息对象
	 * @param member 聊天成员
	 */
	private void sendMessage(DiscussItems item, ChatMember member) {
		PrintWriter out = null;
		try {
			if (member != null) {
				out = member.getAsyncContext().getResponse().getWriter();
				out.write(toJsonp(item));
				out.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 班级内广播
	 * 
	 * @param classId
	 *            班级id
	 * @param memberIdList
	 *            接受者集合
	 * @param exceptMember
	 *            排除的用户(不发送消息至该用户)
	 * @param message
	 *            广播消息
	 * @throws IOException
	 */
	public void broadcast(Collection<String> memberIdList, String exceptUserId,
			DiscussItems item) {
		CometContext cm = CometContext.getInstance();
		for (String memberId : memberIdList) {
			ChatMember member = cm.getMember(memberId);
			if (member == null || member.getMemberId().equals(exceptUserId)) {
				continue;
			}
			sendMessage(item, member);
		}

	}

	public void sendNotifications(ChatMember member, DiscussItems item) {
		if (member == null) {
			return;
		}
		sendMessage(item, member);

	}

	/**
	 * 
	 * 用户登陆退出发送消息
	 * 
	 * @param user
	 * @param command
	 */
	public void logEvent(ShiroUser user, CometCommand command, String message) {
		// 用户登录的时候,要发送消息到其已经加入的讨论组
		Collection<Set<String>> values = GroupCache.getInstance().allValues();
		Set<String> list = null;
		DiscussItems item = new DiscussItems();
		item.setDomain(CometDomain.group.value());
		item.setCommand(command.value());
		item.setSendUserId(user.getId());
		item.setSendUserName(user.getName());
		item.setContext(message);
		item.setSendDate(DateUtil.getDateString());
		item.setSendTime(DateUtil.getTimeString());

		for (Iterator<Set<String>> iter = values.iterator(); iter.hasNext();) {
			list = iter.next();
			if (list.contains(user.getId())) {
				this.broadcast(list, user.getId(), item);
			}
		}
	}

	/**
	 * 用户上线
	 * 
	 * @param user
	 * @param ac
	 * @throws IOException
	 */
	public void login(ShiroUser user, AsyncContext ac) throws IOException {
		CometContext cc = CometContext.getInstance();
		ChatMember oldMember = cc.getMember(user.getId());
		boolean shareDesktop = false;
		if (oldMember != null) {
			shareDesktop = oldMember.isShareDesktop();
			DiscussItems item = new DiscussItems();
			item.setDomain(CometDomain.main.value());
			item.setCommand(CometCommand.repeatLogin.value());
			item.setSendUserId(user.getId());
			item.setSendUserName(user.getName());
			item.setSendDate(DateUtil.getDateString());
			item.setSendTime(DateUtil.getTimeString());

			this.sendNotifications(oldMember, item);
		}
		final ChatMember member = new ChatMember(user.getId(), user.getName(),
				user.getUserType(), ac, shareDesktop);
		cc.addMember(user.getId(), member);
	}

	/**
	 * 用户下线
	 * 
	 * @param userId
	 *            用户id
	 * @throws IOException
	 * 
	 */
	public void logout(ShiroUser user) throws IOException {
		CometContext.getInstance().removeMember(user.getId());
		// 发送退出消息
		logEvent(user, CometCommand.logout, "退出");

	}

	private String toJsonp(DiscussItems item) {
		return "<script type='text/javascript'>window.parent.receive(" + item
				+ ");</script>\n";
		// return
		// "<script type='text/javascript'>alert(window.name);window.parent.receive("+item+");</script>\n";
	}

}
